import { message } from 'antd'
import axios from 'axios'
import history from './history'
import { getToken, removeToken } from './storage'
export const baseURL = 'http://geek.itheima.net/v1_0/'

const instance = axios.create({
  baseURL,
  timeout: 5000,
})

// 请求拦截器
instance.interceptors.request.use(
  function (config) {
    const token = getToken()
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)

// 响应拦截器
instance.interceptors.response.use(
  function (response) {
    return response.data
  },
  function (error) {
    if (error?.response?.status === 401) {
      // token过期
      removeToken()
      history.push('/login', { pathname: history.location.pathname })
      message.warning('用户信息已过期')
    }

    return Promise.reject(error)
  }
)

export default instance
